package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取请求提交的要下载的文件名
        request.setCharacterEncoding("utf-8");
        String filename = request.getParameter("filename");
        //2. 创建输入流指向于 `D:\\download\\` 下的指定的文件
        File file = new File("D:\\baidu\\数据库资料\\day06-Request+Response\\04_作业\\day06-Request&Response\\素材\\编码题目二\\软件包\\download\\" + filename);
        FileInputStream fis = new FileInputStream(file);
        System.out.println(file.getName());
        //3. 设置 `Content-Disposition` 响应头 。如： `resp.setHeader("Content-Disposition","attachment;filename=mysql-5.7.24-winx64.zip");`
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+file.getName());
        //4. 通过response对象获取输出流对象
        ServletOutputStream os = response.getOutputStream();
        //5. 读写数据
        byte[] buf = new byte[1024*8];
        int len = -1;
        while((len=fis.read(buf))!=-1){
            os.write(buf, 0,len);
        }
        //6. 释放资源
        fis.close();
    }
}